package com.ybcj.controller;

import com.ybcj.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 测试请求参数接收
 */
@Controller
@ResponseBody
public class RequestController {
    final String STATUS = "OK";

    // 原始方法
    @RequestMapping("/simpleParamOri")
    public String simpleParamOri(HttpServletRequest request) {
        String name = request.getParameter("name");
        String ageStr = request.getParameter("age");
        int age = Integer.parseInt(ageStr);

        System.out.println(name + ":" + age);
        return STATUS;
    }

    // SpringBoot 方式
    @RequestMapping("/simpleParam")
    public String simpleParam(String name, int age) {
        System.out.println(name + ":" + age);
        return STATUS;
    }

    // 参数映射
    @RequestMapping("/simpleParamMapping")
    public String simpleParamMapping(@RequestParam(value = "name", required = false) String username, int age){
        System.out.println(username + ":" + age);
        return STATUS;
    }

    // 简单实体类
    @RequestMapping("/simpleParamPojo")
    public String simpleParamPojo(User user){
        System.out.println(user.getName() + ":" + user.getAge());
        System.out.println(user);
        return STATUS;
    }

    // 复合实体类
    @RequestMapping("/complexPojo")
    public String complexPojo(User user) {
        System.out.println(user);
        return STATUS;
    }

    // 数组参数接收
    @RequestMapping("/arrayParam")
    public String arrayParam(String[] hobby) {
        System.out.println(Arrays.toString(hobby));
        return STATUS;
    }

    // 集合参数接收
    @RequestMapping("/listParam")
    public String listParam(@RequestParam List<String> hobby) {
        System.out.println(hobby);
        return STATUS;
    }

    // 路径参数接收
    @RequestMapping("/path/{id}")
    public String pathParam(@PathVariable Integer id) {
        System.out.println(id);
        return  STATUS;
    }

    @RequestMapping("/path/{id}/{name}")
    public String pathParam2(@PathVariable Integer id, @PathVariable String name) {
        System.out.println("ID:" + id + ",name:" + name);
        return STATUS;
    }

    // 时间参数接收
    @RequestMapping("/datetimeParam")
    public String datetimeParam(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime updateTime){
        System.out.println(updateTime);
        return STATUS;
    }

    // json参数接收
    @RequestMapping("/jsonParam")
    public String jsonParam(@RequestBody User user) {
        System.out.println(user);
        return STATUS;
    }
}
